import SpaceHeader from '@/components/space-header/index'
import EmployeeLogin from '@/apis/EmployeeLogin.js'
import JobinfoQuery from '@/apis/JobinfoQuery'

export default {
  name: 'Login',
  components: {
    SpaceHeader,
  },
  data() {
    return {
      loginInfo: {
        phone: '13987332016',
        password: '123456',
      },
    }
  },
  methods: {
    login() {
      // 测试环境
      if (this.$store.state.env === 'test') {
        // 初步判断表单
        if (this.loginInfo.phone === '' || this.loginInfo.password === '') {
          this.$toast('输入的手机号或者密码不能为空')
          return
        } else if (this.loginInfo.phone.length !== 11) {
          this.$toast('请输入正确的手机号')
          return
        } else if (
          this.loginInfo.password.length > 20 ||
          this.loginInfo.password.length < 6
        ) {
          this.$toast('请输入正确的密码')
          return
        }
        // 账号登录
        EmployeeLogin({
          phone: this.loginInfo.phone,
          password: this.loginInfo.password,
        }).then((res) => {
          // console.log(res)
          if (res.data.authenticated === true) {
            this.$toast('登录成功')
            this.$store.commit('initUserInfo', res.data.principal)
            this.$store.commit('initAuthorization', res.header.Authorization)
            this.$store.commit(
              'initRole',
              res.data.authorities[0].role
                .split('_')
                .splice(1)
                .join('_')
            )
            // 获取岗位信息
            if (this.$store.state.userInfo) {
              JobinfoQuery(
                {
                  jobNumber: this.$store.state.userInfo.jobNumber,
                },
                this.$store.state.authorization
              ).then((res) => {
                this.$store.commit('initPostInfo', res.data.data)
                // console.log(res)
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/pages/main/index',
                  })
                }, 600)
              })
            }
          } else {
            // TODO:检测登录接口输出值
            this.$toast(res.data.message)
          }
        })
      }
      // 开发环境
      else if (this.$store.state.env === 'dev') {
        this.$toast('登录成功')
        uni.reLaunch({
          url: '/pages/main/index',
        })
      }
    },
    goTo(goal) {
      uni.navigateTo({
        url: goal,
      })
      setTimeout(() => {
        this.loginInfo = {
          phone: '',
          password: '',
        }
      }, 200)
    },
  },
}
